 ///
 /// @file    map.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-05-03 15:16:54
 ///
 
#include <map>
#include <iostream>
using std::cout;
using std::endl;
using std::map;
using std::string;
 
void test0() 
{
	//map中存放的元素是pair类型
	//
	//map中元素默认情况下，按升序方式进行排列
	//map中不能存放关键字相同的元素
	//
	//底层实现：红黑树
	map<string, string> cities{
		{"027", "武汉"},
		{"021", "上海"},
		{"022", "天津"},
		{"0755", "深圳"},
		{"010", "南京"},
	};
	for(auto & elem : cities) {
		cout << elem.first << " --> " << elem.second << endl;
	}

	//使用下标访问运算符, 时间复杂度O(logN)
	cout << cities["027"] << endl;//通过key直接拿到value

	cities["010"] = "北京";//可以直接通过key修改相应的value

	for(auto & elem : cities) {
		cout << elem.first << " --> " << elem.second << endl;
	}
	//key 023并不在map中, 执行完下标访问运算符之后，
	//023的key会添加到map之中去
	cout << " cities[023]:" << cities["023"]  << endl;
	for(auto & elem : cities) {
		cout << elem.first << " --> " << elem.second << endl;
	}

	cities["0310"] = "邯郸";//添加一个新元素
} 

void test1()
{
	map<string, string> cities{
		{"027", "武汉"},
		{"021", "上海"},
		{"022", "天津"},
		{"0755", "深圳"},
		{"010", "南京"},
	};
	for(auto & elem : cities) {
		cout << elem.first << " --> " << elem.second << endl;
	}
	cout << endl;

	auto lowerit = cities.lower_bound("022");
	cout << lowerit->first << " --> " << lowerit->second << endl;
	auto upperit = cities.upper_bound("022");
	cout << upperit->first << " --> " << upperit->second << endl;

	cout << endl;
	auto ret = cities.equal_range("022");
	cout << ret.first->first << " --> " << ret.first->second << endl;
	cout << ret.second->first << " --> " << ret.second->second << endl;
}

void test2()
{
	map<string, string> cities{
		{"027", "武汉"},
		{"021", "上海"},
		{"022", "天津"},
		{"0755", "深圳"},
		{"010", "南京"},
	};
	//auto ret = cities.insert(std::make_pair("0310", "邯郸"));
	std::pair<map<string,string>::iterator, bool>
		ret = cities.insert(std::make_pair("0310", "邯郸"));
	if(ret.second) {
		cout << "添加成功" << endl;
	} else {
		cout << "添加失败" << endl;
	}
	cout << ret.first->first << " --> " << ret.first->second << endl;

}
 
int main(void)
{
	/* test0(); */
	/* test1(); */
	test2();
	return 0;
}
